﻿using System.Collections.Generic;
using System.Threading;

namespace System.Dns.Toolkit.DnsServer {

    public class ThreadPoolMessageDispatcher : IMessageDispatcher {

        private readonly Dictionary<Type, ICore> _actions = new Dictionary<Type, ICore>();

        private volatile bool _suspend;

        public ThreadPoolMessageDispatcher() {
            _suspend = false;
        }

        public void Subscribe(ICore icore, Type t) {
            lock (_actions) {
                if (!_actions.ContainsKey(t)) {
                    _actions[t] = icore;
                }
            }
        }

        public bool Publish<T>(T message) {

            var t = typeof(T);
            Console.WriteLine("{0} - Publish {1} : {2}", Thread.CurrentThread.ManagedThreadId, t.Name, message);

            if (_suspend) {
                return false;
            }

            if (!_actions.ContainsKey(t)) {
                return false;
            }

            ThreadPool.QueueUserWorkItem(_actions[t].MessageReceived, message);
            return true;
        }

    }
}
